<script setup>
import { ref, onMounted, reactive, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { getstatistics } from '@/api/statis'

const pieChartRef = ref(null)
let pieChart = null

// 设置默认的开始和结束时间
const startTime = ref(new Date('2020-10-04T12:34:56'))
const endTime = ref(new Date('2026-11-04T12:34:56'))

const statistics = reactive({
  PAYED: 0,
  REFUND: 0,
  REFUNDED: 0,
  CANCELED: 0,
  USED: 0,
  averageOrdersPerDay: 0,
  totalOrders: 0,
  NON_PAYMENT: 0
})

// 处理开始时间变化
const handleStartTimeChange = (val) => {
  startTime.value = val
}

// 处理结束时间变化
const handleEndTimeChange = (val) => {
  endTime.value = val
}

// 初始化饼图
const initPieChart = () => {
  pieChart = echarts.init(pieChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: statistics.PAYED, name: '已支付' },
          { value: statistics.REFUND, name: '退款中' },
          { value: statistics.REFUNDED, name: '已退款' },
          { value: statistics.CANCELED, name: '已取消' },
          { value: statistics.USED, name: '已使用' },
          { value: statistics.NON_PAYMENT, name: '未支付' }
        ]
      }
    ]
  }
  pieChart.setOption(option)
}

// 获取统计数据
const fetchStatistics = async () => {
  if (!startTime.value || !endTime.value) {
    return
  }

  // 格式化日期为指定格式
  const formatDate = (date) => {
    return date.toISOString().split('.')[0] // Remove milliseconds and get format like "2020-10-04T12:34:56"
  }

  const params = {
    startTime: formatDate(startTime.value),
    endTime: formatDate(endTime.value)
  }

  try {
    const res = await getstatistics(params)
    if (res.code === 1 && res.data) {
      Object.assign(statistics, res.data)
      initPieChart()
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  pieChart && pieChart.resize()
}

onMounted(() => {
  fetchStatistics()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  pieChart && pieChart.dispose()
})
</script>

<template>
  <div class="statistics-container">
    <!-- 时间选择器 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card shadow="hover">
          <el-space>
            <el-date-picker
              v-model="startTime"
              type="datetime"
              placeholder="开始时间"
              @change="handleStartTimeChange"
            />
            <el-date-picker
              v-model="endTime"
              type="datetime"
              placeholder="结束时间"
              @change="handleEndTimeChange"
            />
            <el-button type="primary" @click="fetchStatistics">
              查询
            </el-button>
          </el-space>
        </el-card>
      </el-col>
    </el-row>

    <!-- 头部统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单总量</span>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalOrders }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>日均订单量</span>
            </div>
          </template>
          <div class="card-value">
            {{ statistics.averageOrdersPerDay.toFixed(2) }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已支付订单</span>
            </div>
          </template>
          <div class="card-value">{{ statistics.PAYED }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已使用订单</span>
            </div>
          </template>
          <div class="card-value">{{ statistics.USED }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单状态分布饼图 -->
    <el-row class="mt-4">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div class="chart-container" ref="pieChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.statistics-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  text-align: center;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.mt-4 {
  margin-top: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>
